"""
得捷(DigiKey)数字化解决方案本地服务HTTP代理到HTTPS服务

作者：HonestQiao
版本：V1.0
时间：2024-01-22

参考：
A simple proxy server, based on original by gear11:
https://gist.github.com/gear11/8006132
"""

import re
import urllib3
from urllib.parse import urlparse, urlunparse
from flask import Flask, render_template, request, abort, Response, redirect
import requests
import logging

# 实际请求的网址前缀
HTTPS_URI = "https://127.0.0.1:8888"

# 允许请求的网址
# APPROVED_HOSTS = set(["127.0.0.1:8888"])
# CHUNK_SIZE = 1024

# HTTPS请求警告抑制
urllib3.disable_warnings()

# FLask实例
app = Flask(__name__.split('.')[0])

# 日志设置
logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger(__name__)

# 代理路径
@app.route('/<path:url>', methods=["GET", "POST"])
def proxy(url):
    # 实际请求网址
    request_url = "%s/%s%s" % (HTTPS_URI, url, ("?" + request.query_string.decode('utf-8') if request.query_string else ""))

    # 发起请求
    # LOG.debug("%s %s with headers: %s", request.method, request_url, request.headers)
    # r = make_request(request_url, request.method, dict(request.headers), request.form)
    data = None
    LOG.debug("Sending %s %s with headers: %s and data %s", request.method, request_url, request.headers, data)
    r = requests.request(request.method, request_url, params=request.args, stream=True, headers=request.headers, allow_redirects=False, data=data, verify=False)

    LOG.debug("Got %s response from %s",r.status_code, request_url)
    headers = dict(r.raw.headers)
    def generate():
        for chunk in r.raw.stream(decode_content=False):
            yield chunk
    # 返回数据
    out = Response(generate(), headers=headers)
    out.status_code = r.status_code
    return out

# 实际请求处理
def make_request(url, method, headers={}, data=None):
    # 网络请求调用
    LOG.debug("Sending %s %s with headers: %s and data %s", method, url, headers, data)
    return requests.request(method, url, params=request.args, stream=True, headers=headers, allow_redirects=False, data=data, verify=False)

app.run(
    debug=True, host="0.0.0.0", port=8889
)